<template>
  <div class="feedback">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">
        <el-icon><ChatDotRound /></el-icon>
        活动反馈
      </h2>
      <div class="header-actions">
        <el-button @click="loadFeedbacks" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新建反馈
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="活动">
          <el-select
            v-model="filterForm.activityId"
            placeholder="选择活动"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="activity in availableActivities"
              :key="activity.id"
              :label="activity.title"
              :value="activity.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="反馈类型">
          <el-select
            v-model="filterForm.type"
            placeholder="选择类型"
            clearable
            style="width: 150px"
          >
            <el-option label="活动体验" value="EXPERIENCE" />
            <el-option label="组织建议" value="SUGGESTION" />
            <el-option label="问题反馈" value="ISSUE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="评分">
          <el-select
            v-model="filterForm.rating"
            placeholder="选择评分"
            clearable
            style="width: 120px"
          >
            <el-option label="5星" :value="5" />
            <el-option label="4星" :value="4" />
            <el-option label="3星" :value="3" />
            <el-option label="2星" :value="2" />
            <el-option label="1星" :value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            筛选
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 反馈列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <span class="list-title">
            我的反馈
            <el-tag v-if="total > 0" type="info" size="small">
              共 {{ total }} 条反馈
            </el-tag>
          </span>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="feedbacks.length === 0" class="empty-container">
        <el-empty description="暂无反馈记录">
          <el-button type="primary" @click="showCreateDialog">
            创建第一个反馈
          </el-button>
        </el-empty>
      </div>
      
      <!-- 反馈列表 -->
      <div v-else class="feedback-list">
        <div 
          v-for="feedback in feedbacks" 
          :key="feedback.id"
          class="feedback-item"
        >
          <div class="item-header">
            <div class="activity-info">
              <h3 class="activity-title" @click="goToActivity(feedback.activity.id)">
                {{ feedback.activity.title }}
              </h3>
              <div class="feedback-meta">
                <el-tag :type="getTypeColor(feedback.type)" size="small">
                  {{ getTypeText(feedback.type) }}
                </el-tag>
                <el-rate
                  v-model="feedback.rating"
                  disabled
                  size="small"
                  show-score
                  text-color="#ff9900"
                />
                <span class="feedback-time">{{ formatDate(feedback.createTime, 'MM-DD HH:mm') }}</span>
              </div>
            </div>
            <div class="item-actions">
              <el-button size="small" @click="viewFeedback(feedback)">
                查看
              </el-button>
              <el-button size="small" type="primary" @click="editFeedback(feedback)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="deleteFeedback(feedback)">
                删除
              </el-button>
            </div>
          </div>
          
          <div class="item-content">
            <p class="feedback-content">{{ feedback.content }}</p>
            
            <div v-if="feedback.images?.length > 0" class="feedback-images">
              <el-image
                v-for="(image, index) in feedback.images"
                :key="index"
                :src="image"
                :preview-src-list="feedback.images"
                :initial-index="index"
                class="feedback-image"
                fit="cover"
              />
            </div>
            
            <div v-if="feedback.reply" class="feedback-reply">
              <div class="reply-header">
                <el-icon><ChatDotRound /></el-icon>
                <span>组织者回复</span>
                <span class="reply-time">{{ formatDate(feedback.reply.createTime, 'MM-DD HH:mm') }}</span>
              </div>
              <div class="reply-content">{{ feedback.reply.content }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑反馈对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑反馈' : '创建反馈'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="feedbackForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="选择活动" prop="activityId">
          <el-select
            v-model="feedbackForm.activityId"
            placeholder="请选择要反馈的活动"
            filterable
            style="width: 100%"
            :disabled="isEdit"
          >
            <el-option
              v-for="activity in availableActivities"
              :key="activity.id"
              :label="activity.title"
              :value="activity.id"
            >
              <div class="activity-option">
                <div class="option-title">{{ activity.title }}</div>
                <div class="option-meta">{{ formatDate(activity.startTime, 'MM-DD') }} | {{ activity.location }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="反馈类型" prop="type">
          <el-select v-model="feedbackForm.type" placeholder="请选择反馈类型" style="width: 100%">
            <el-option label="活动体验" value="EXPERIENCE" />
            <el-option label="组织建议" value="SUGGESTION" />
            <el-option label="问题反馈" value="ISSUE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动评分" prop="rating">
          <el-rate
            v-model="feedbackForm.rating"
            show-text
            :texts="['极差', '失望', '一般', '满意', '惊喜']"
          />
        </el-form-item>
        
        <el-form-item label="反馈内容" prop="content">
          <el-input
            v-model="feedbackForm.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您的反馈内容..."
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="上传图片">
          <el-upload
            v-model:file-list="feedbackForm.imageList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="5"
            accept="image/*"
            @change="handleImageChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传5张图片，支持jpg、png格式</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitFeedback" :loading="submitting">
            {{ isEdit ? '更新' : '提交' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看反馈对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="反馈详情"
      width="600px"
    >
      <div v-if="currentFeedback" class="feedback-detail">
        <div class="detail-header">
          <h3>{{ currentFeedback.activity?.title }}</h3>
          <div class="detail-meta">
            <el-tag :type="getTypeColor(currentFeedback.type)" size="small">
              {{ getTypeText(currentFeedback.type) }}
            </el-tag>
            <el-rate
              :model-value="currentFeedback.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
          </div>
        </div>
        
        <div class="detail-content">
          <h4>反馈内容</h4>
          <p>{{ currentFeedback.content }}</p>
          
          <div v-if="currentFeedback.images?.length > 0" class="detail-images">
            <h4>相关图片</h4>
            <el-image
              v-for="(image, index) in currentFeedback.images"
              :key="index"
              :src="image"
              :preview-src-list="currentFeedback.images"
              :initial-index="index"
              class="detail-image"
              fit="cover"
            />
          </div>
          
          <div v-if="currentFeedback.reply" class="detail-reply">
            <h4>组织者回复</h4>
            <div class="reply-box">
              <div class="reply-meta">
                <span>{{ formatDate(currentFeedback.reply.createTime) }}</span>
              </div>
              <div class="reply-text">{{ currentFeedback.reply.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { formatDate, debounce } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  ChatDotRound,
  Refresh,
  Plus,
  Search
} from '@element-plus/icons-vue'

const router = useRouter()

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)

const feedbacks = ref([])
const total = ref(0)
const availableActivities = ref([])
const currentFeedback = ref(null)

const filterForm = reactive({
  activityId: '',
  type: '',
  rating: ''
})

const pagination = reactive({
  page: 1,
  size: 10
})

const feedbackForm = reactive({
  id: null,
  activityId: '',
  type: '',
  rating: 5,
  content: '',
  imageList: []
})

const formRef = ref()

const formRules = {
  activityId: [
    { required: true, message: '请选择活动', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择反馈类型', trigger: 'change' }
  ],
  rating: [
    { required: true, message: '请给活动评分', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入反馈内容', trigger: 'blur' },
    { min: 10, message: '反馈内容至少10个字符', trigger: 'blur' }
  ]
}

const getTypeColor = (type) => {
  const colorMap = {
    EXPERIENCE: 'success',
    SUGGESTION: 'primary',
    ISSUE: 'warning',
    OTHER: 'info'
  }
  return colorMap[type] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    EXPERIENCE: '活动体验',
    SUGGESTION: '组织建议',
    ISSUE: '问题反馈',
    OTHER: '其他'
  }
  return textMap[type] || type
}

const loadFeedbacks = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...filterForm
    }
    
    const response = await api.get('/feedbacks/my', { params })
    const { data, total: totalCount } = response.data.data
    
    feedbacks.value = data || []
    total.value = totalCount || 0
    
  } catch (error) {
    console.error('加载反馈列表失败:', error)
    ElMessage.error('加载反馈列表失败')
  } finally {
    loading.value = false
  }
}

const loadAvailableActivities = async () => {
  try {
    const response = await api.get('/registrations/my-activities', {
      params: { status: 'APPROVED' }
    })
    
    const activities = response.data.data || []
    // 只显示已结束的活动
    availableActivities.value = activities
      .map(reg => reg.activity)
      .filter(activity => {
        const endTime = new Date(activity.endTime)
        return endTime < new Date()
      })
    
  } catch (error) {
    console.error('加载可反馈活动失败:', error)
  }
}

const handleFilter = debounce(() => {
  pagination.page = 1
  loadFeedbacks()
}, 300)

const handleReset = () => {
  Object.assign(filterForm, {
    activityId: '',
    type: '',
    rating: ''
  })
  pagination.page = 1
  loadFeedbacks()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadFeedbacks()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadFeedbacks()
}

const showCreateDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const editFeedback = (feedback) => {
  isEdit.value = true
  Object.assign(feedbackForm, {
    id: feedback.id,
    activityId: feedback.activity.id,
    type: feedback.type,
    rating: feedback.rating,
    content: feedback.content,
    imageList: feedback.images?.map((url, index) => ({
      uid: index,
      name: `image-${index}`,
      url
    })) || []
  })
  dialogVisible.value = true
}

const viewFeedback = (feedback) => {
  currentFeedback.value = feedback
  viewDialogVisible.value = true
}

const deleteFeedback = async (feedback) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条反馈吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/feedbacks/${feedback.id}`)
    
    ElMessage.success('删除成功')
    loadFeedbacks()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除反馈失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handleImageChange = (file, fileList) => {
  feedbackForm.imageList = fileList
}

const submitFeedback = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const formData = new FormData()
    formData.append('activityId', feedbackForm.activityId)
    formData.append('type', feedbackForm.type)
    formData.append('rating', feedbackForm.rating)
    formData.append('content', feedbackForm.content)
    
    // 处理图片上传
    feedbackForm.imageList.forEach((file, index) => {
      if (file.raw) {
        formData.append('images', file.raw)
      }
    })
    
    if (isEdit.value) {
      await api.put(`/feedbacks/${feedbackForm.id}`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      ElMessage.success('更新成功')
    } else {
      await api.post('/feedbacks', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      ElMessage.success('提交成功')
    }
    
    dialogVisible.value = false
    loadFeedbacks()
    
  } catch (error) {
    console.error('提交反馈失败:', error)
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  Object.assign(feedbackForm, {
    id: null,
    activityId: '',
    type: '',
    rating: 5,
    content: '',
    imageList: []
  })
  formRef.value?.resetFields()
}

const goToActivity = (activityId) => {
  router.push(`/student/activities/${activityId}`)
}

onMounted(() => {
  loadFeedbacks()
  loadAvailableActivities()
})
</script>

<style scoped>
.feedback {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  margin-bottom: 0;
}

.list-card {
  min-height: 400px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.loading-container,
.empty-container {
  padding: 40px 20px;
  text-align: center;
}

.feedback-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.feedback-item {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
  transition: all 0.3s ease;
}

.feedback-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.activity-info {
  flex: 1;
}

.activity-title {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
  margin: 0 0 8px 0;
  cursor: pointer;
}

.activity-title:hover {
  text-decoration: underline;
}

.feedback-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.feedback-time {
  font-size: 14px;
  color: #909399;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.item-content {
  margin-top: 16px;
}

.feedback-content {
  color: #606266;
  line-height: 1.6;
  margin: 0 0 16px 0;
}

.feedback-images {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.feedback-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
}

.feedback-reply {
  background: #f8f9fa;
  border-left: 4px solid #409eff;
  padding: 16px;
  border-radius: 4px;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-weight: 600;
  color: #303133;
}

.reply-time {
  margin-left: auto;
  font-size: 14px;
  color: #909399;
  font-weight: normal;
}

.reply-content {
  color: #606266;
  line-height: 1.6;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 对话框样式 */
.activity-option {
  padding: 4px 0;
}

.option-title {
  font-weight: 600;
  color: #303133;
}

.option-meta {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.dialog-footer {
  text-align: right;
}

/* 查看反馈对话框 */
.feedback-detail {
  padding: 0;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.detail-header h3 {
  margin: 0 0 12px 0;
  color: #303133;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.detail-content h4 {
  margin: 20px 0 12px 0;
  color: #303133;
  font-size: 16px;
}

.detail-content p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.detail-images {
  margin-top: 20px;
}

.detail-image {
  width: 100px;
  height: 100px;
  margin-right: 12px;
  margin-bottom: 12px;
  border-radius: 4px;
  cursor: pointer;
}

.detail-reply {
  margin-top: 20px;
}

.reply-box {
  background: #f8f9fa;
  border-left: 4px solid #409eff;
  padding: 16px;
  border-radius: 4px;
}

.reply-meta {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.reply-text {
  color: #606266;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .filter-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  
  .item-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .item-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .feedback-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>